package cn.jeeweb.modules.client.controller;

import cn.jeeweb.core.model.AjaxJson;
import cn.jeeweb.core.model.PageJson;
import cn.jeeweb.core.query.data.PropertyPreFilterable;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.query.utils.QueryableConvertUtils;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jeeweb.core.utils.MessageUtils;
import cn.jeeweb.core.utils.ObjectUtils;
import cn.jeeweb.core.utils.StringUtils;
import cn.jeeweb.core.utils.http.HttpRequestUtils;
import cn.jeeweb.core.utils.upload.exception.FileNameLengthLimitExceededException;
import cn.jeeweb.core.utils.upload.exception.InvalidExtensionException;
import cn.jeeweb.modules.client.entity.ClientUser;
import cn.jeeweb.modules.client.entity.Shop;
import cn.jeeweb.modules.client.service.IClientUserService;
import cn.jeeweb.modules.client.service.IShopService;
import cn.jeeweb.modules.sys.entity.Attachment;
import cn.jeeweb.modules.sys.service.IAttachmentService;
import cn.jeeweb.modules.sys.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileUploadBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jeeweb.core.common.controller.BaseBeanController;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.jeeweb.modules.client.entity.Task;
import cn.jeeweb.modules.client.service.ITaskService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Title: 订单任务
 * @Description: 订单任务
 * @author zhuht
 * @date 2018-04-13 22:05:39
 * @version V1.0
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/client/task")
@RequiresPathPermission("client:task")
public class TaskController extends BaseBeanController<Task> {

    @Autowired
    private ITaskService taskService;

    @Autowired
    protected IShopService shopService;

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    protected IClientUserService clientUserService;

    public Task get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return taskService.selectById(id);
        } else {
            return newModel();
        }
    }

    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<Task> entityWrapper = new EntityWrapper<Task>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        //entityWrapper.eq("status", 0);
        entityWrapper.eq("createBy.id", UserUtils.getUser().getId());
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Task> pagejson = new PageJson<Task>(taskService.list(queryable,entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response,Queryable queryable) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
       /* EntityWrapper<Shop> entityWrapper = new EntityWrapper<Shop>(Shop.class);
        entityWrapper.eq("createBy.id", UserUtils.getUser().getId());

        model.addAttribute("shops", shopService.listWithNoPage(queryable,entityWrapper));*/

        EntityWrapper<ClientUser> entityWrapper = new EntityWrapper<ClientUser>(ClientUser.class);
        entityWrapper.eq("createBy.id", UserUtils.getUser().getId());
        model.addAttribute("users", clientUserService.listWithNoPage(queryable,entityWrapper));

        return display("edit");
    }

    /**
     * 获取京东信息
     */
    @RequestMapping(value = "searchJdlink", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson searchJdlink(String link) {
        AjaxJson ajaxJson = new AjaxJson();
        if(link==null||"".equals(link)){
            ajaxJson.fail("请输入链接");
            return ajaxJson;
        }

        try{
            String sku = link.substring(link.indexOf("https://item.jd.com/")+20, link.lastIndexOf(".html"));
            JSONObject reponseStr = HttpRequestUtils.httpGet("https://way.jd.com/JDCloud/baseproduct?ids="+sku+"&basefields=shopCategorys,weight,name,imagePath,shopName,skuMark,shopCategorys&appkey=751f3c86e1c733527b99f047d6d6c4b2");
            ajaxJson.success("查询成功");
            ajaxJson.put("info", reponseStr);
        }catch(Exception e){
            e.printStackTrace();
            ajaxJson.fail("查询失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") Task task, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(task, request, response, result);
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                         HttpServletResponse response,Queryable queryable) {
        Task task = get(id);
        model.addAttribute("data", task);
      /*  EntityWrapper<Shop> entityWrapper = new EntityWrapper<Shop>(Shop.class);
        entityWrapper.eq("createBy.id", UserUtils.getUser().getId());

        model.addAttribute("shops", shopService.listWithNoPage(queryable,entityWrapper));*/

        EntityWrapper<ClientUser> entityWrapper = new EntityWrapper<ClientUser>(ClientUser.class);
        entityWrapper.eq("createBy.id", UserUtils.getUser().getId());
        model.addAttribute("users", clientUserService.listWithNoPage(queryable,entityWrapper));
        return display("edit");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") Task task, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(task, request, response, result);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(Task task, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");

        if (hasError(task, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            //task.setUserId(UserUtils.getUser().getId());
            if (StringUtils.isEmpty(task.getId())) {
                taskService.insert(task);
            } else {
                taskService.insertOrUpdate(task);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids[]", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            taskService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    /**
     *
     * @title: ajaxUpload
     * @description: 文件上传
     * @param request
     * @param response
     * @param files
     * @return
     * @return: AjaxUploadResponse
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson upload(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/plain");
        AjaxJson ajaxJson = new AjaxJson();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<Attachment> attachmentList = new ArrayList<Attachment>();
        if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> ite = multiRequest.getFileNames();
            while (ite.hasNext()) {
                MultipartFile file = multiRequest.getFile(ite.next());
                try {
                    Attachment attachment = attachmentService.upload(request, file);
                    attachmentList.add(attachment);
                    continue;
                } catch (IOException e) {
                    ajaxJson.fail(MessageUtils.getMessage("upload.server.error"));
                    continue;
                } catch (InvalidExtensionException e) {
                    ajaxJson.fail(MessageUtils.getMessage("upload.server.error"));
                    continue;
                } catch (FileUploadBase.FileSizeLimitExceededException e) {
                    ajaxJson.fail(MessageUtils.getMessage("upload.server.error"));
                    continue;
                } catch (FileNameLengthLimitExceededException e) {
                    ajaxJson.fail(MessageUtils.getMessage("upload.server.error"));
                    continue;
                }
            }

            ajaxJson.setData(attachmentList);
        }
        return ajaxJson;
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            taskService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson delete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            taskService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }


    @RequestMapping(value = "batch/commit", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchCommit() {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("提交成功");
        try {
            taskService.commitOrder(UserUtils.getUser().getId());
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("提交失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "copyView", method = RequestMethod.GET)
    public String copyView(Model model, HttpServletRequest request,
                       HttpServletResponse response,Queryable queryable) {
        return display("copy");
    }

    @RequestMapping(value = "{id}/copy", method = RequestMethod.GET)
    public String copy(@PathVariable("id") String id, Model model, HttpServletRequest request,
                         HttpServletResponse response,Queryable queryable) {
        Task task = get(id);
        task.setId(null);
        model.addAttribute("data", task);

        EntityWrapper<ClientUser> entityWrapper = new EntityWrapper<ClientUser>(ClientUser.class);
        model.addAttribute("users", clientUserService.listWithNoPage(queryable,entityWrapper));
        return display("edit");
    }

    //导入EXCEL
    @RequestMapping(value="import")
    @ResponseBody
    public AjaxJson saveImport(HttpServletRequest request, @RequestParam("file") MultipartFile file)throws Exception{
        AjaxJson ajaxJson = new AjaxJson();
        if (file.isEmpty()) {
            ajaxJson.fail("不能导入空的文件");
        }
        if (this.taskService.saveImport(file)) {
            ajaxJson.success("导入成功");
        }
        return ajaxJson;
    }

}
